import 'package:flutter/material.dart';

class LineProgressBar extends StatelessWidget {
  final double startPoint; // 线的起点
  final double strokeWidth; // 线的高度
  final double lineWidth; // 线的长度
  final double value; // 进度值
  final Color backgroundColor; // 线的背景色
  final Color foregroundColor; // 线的颜色
  final StrokeCap strokeCap;

  const LineProgressBar({
    super.key,
    this.startPoint = 0,
    this.strokeWidth = 10,
    this.lineWidth = 10,
    this.value = 0,
    this.backgroundColor = Colors.grey, // 线的背景色
    this.foregroundColor = Colors.blue,
    this.strokeCap = StrokeCap.round,
  })  : assert(value >= 0 && value <= lineWidth),
        assert(startPoint <= lineWidth);

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: LineProgressBarPainter(
        startPoint: startPoint,
        strokeWidth: strokeWidth,
        lineWidth: lineWidth,
        value: value,
        backgroundColor: backgroundColor,
        foregroundColor: foregroundColor,
        strokeCap: strokeCap,
      ),
    );
  }
}

class LineProgressBarPainter extends CustomPainter {
  final double startPoint;
  final double strokeWidth;
  final double lineWidth; // 线的长度
  final double value; // 进度值
  final Color backgroundColor; // 线的背景色
  final Color foregroundColor; // 线的颜色
  final StrokeCap strokeCap;

  LineProgressBarPainter({
    this.startPoint = 0,
    this.strokeWidth = 10,
    this.lineWidth = 10,
    this.value = 0,
    this.backgroundColor = Colors.grey, // 线的背景色
    this.foregroundColor = Colors.blue,
    this.strokeCap = StrokeCap.round,
  });

  @override
  void paint(Canvas canvas, Size size) {
    //画背景
    var bgPaint = Paint()
      ..isAntiAlias = true
      ..strokeWidth = strokeWidth
      ..strokeCap = strokeCap
      ..color = backgroundColor;

    var fPaint = Paint()
      ..isAntiAlias = true
      ..strokeWidth = strokeWidth
      ..strokeCap = strokeCap
      ..color = foregroundColor;

    canvas.drawLine(Offset(startPoint, 0), Offset(lineWidth, 0), bgPaint);
    // value为0时不绘制进度值
    if (value > 0) {
      canvas.drawLine(Offset(startPoint, 0), Offset(value, 0), fPaint);
    }
  }

  @override
  bool shouldRepaint(LineProgressBarPainter oldDelegate) =>
      value != oldDelegate.value || backgroundColor != oldDelegate.backgroundColor || foregroundColor != oldDelegate.foregroundColor;
}
